﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;

namespace DomainTool
{
    class HttpUtils
    {
        private CookieContainer cookieContainer = new CookieContainer(); // 声明CookieContainer对象
        public static string userAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
        public static string contentType = "Content-Type:application/x-www-form-urlencoded";
        public static string accept = "Accept: */*";

        public static HttpResponseObj httpPost(WebHeaderCollection headers, string url, string postData)
        {
            
            // 登录网站
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            byte[] byteRequest = Encoding.Default.GetBytes(postData);
            httpWebRequest.Method = "POST";

            if (!headers.Get("Accept").Equals(""))
                httpWebRequest.Accept = headers.Get("Accept");
            if (!headers.Get("User-Agent").Equals(""))
                httpWebRequest.Accept = headers.Get("User-Agent");
            if (!headers.Get("Content-Type").Equals(""))
                httpWebRequest.Accept = headers.Get("Content-Type");

            httpWebRequest.ContentLength = byteRequest.Length;
            Stream stream = httpWebRequest.GetRequestStream();
            stream.Write(byteRequest, 0, byteRequest.Length);
            stream.Close();
            HttpResponseObj responseObj = new HttpResponseObj();
            HttpWebResponse response;
            response  = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader myreader = new StreamReader(
            response.GetResponseStream(), Encoding.UTF8);
            string responseText = myreader.ReadToEnd();
           
            responseObj.content = responseText;
            responseObj.headers=response.Headers;
            responseObj.statusCode = response.StatusCode.ToString();
            return responseObj;
        }
        public static string httpGet( string url)
        {

            // 登录网站
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
            httpWebRequest.Method = "GET";
            httpWebRequest.UserAgent = userAgent;
            httpWebRequest.Accept = accept;
            httpWebRequest.ContentType = contentType;
            httpWebRequest.Headers["Accept-Language"] = "zh-cn";
            HttpWebResponse response;
            response = (HttpWebResponse)httpWebRequest.GetResponse();
            StreamReader myreader = new StreamReader(
            response.GetResponseStream(), Encoding.GetEncoding("GBK"));
            string responseText = myreader.ReadToEnd();
            return responseText;
        }
    }
}
